package com.zzw.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @ClassName: VersionCompare
 * @Description: 软件版本比较
 * @author ZZW
 * 
 */
public class VersionCompare {
	private static class VersionStringComparator implements Comparator<String> {
		public int compare(String v1, String v2) {
			if (v1 == null && v2 == null)
				return 0;
			else if (v1 == null)
				return -1;
			else if (v2 == null)
				return 1;

			// 拆分版本号为数组
			String[] arr1 = v1.split("[^a-zA-Z0-9]+");
			String[] arr2 = v2.split("[^a-zA-Z0-9]+");

			int a, b, c;
			for (int i = 0, max = Math.min(arr1.length, arr2.length); i <= max; i++) {

				if (i == arr1.length)
					return i == arr2.length ? 0 : -1;
				else if (i == arr2.length)
					return 1;

				try {
					a = Integer.parseInt(arr1[i]);
					b = Integer.parseInt(arr2[i]);
				} catch (Exception x) {
					a = Integer.MAX_VALUE;
					b = Integer.MAX_VALUE;
				}
				if (a != b) {
					return a - b;
				}
				c = arr1[i].compareTo(arr2[i]);  // 字符串对象之间的比较（字符串中可包含任意字符）
				if (c != 0)
					return c;
			}
			return 0;
		}
	}
	
	public static String VCompare(String v1, String v2) {
		List<String> list = new ArrayList<>();
		list.add(v1);
		list.add(v2);
		Collections.sort(list, new VersionStringComparator());
		return list.get(1);
	}
	
	public static void main(String[] args) {
			System.out.println("较新的版本为：" + VCompare( "bonc_127127-11","bonc_127127-13"));
			System.out.println("较新的版本为：" + VCompare( "1.5","1.5.1"));
			System.out.println("较新的版本为：" + VCompare( "1.5.1","1.6.1"));
			System.out.println("较新的版本为：" + VCompare( "2.0.0","1.9.1"));
			System.out.println("较新的版本为：" + VCompare( "1.6.0_07","1.6.0_07-b01"));
			System.out.println("较新的版本为：" + VCompare( "1.6.0_07","1.6.0.6"));
			System.out.println("较新的版本为：" + VCompare( "2.0.0.16","5.10"));
			System.out.println("较新的版本为：" + VCompare( "1.6.0_08-a06","1.6.0_08-b06"));
	}
	
}
